
#include "Block.h"

USING_NS_CC;

bool Block::init()
{
	m_idx = random(1, 4);
	auto framName = StringUtils::format("block%d.png", m_idx);

	if (!Sprite::initWithSpriteFrameName(framName))
	{
		return false;
	}

	m_speed = Vec2::ZERO;

	auto lis = EventListenerKeyboard::create();

	lis->onKeyPressed = [this](EventKeyboard::KeyCode code, Event*)->void {
		
		if (code == EventKeyboard::KeyCode::KEY_A)
		{
			m_speed.x = -100;
		}
		if (code == EventKeyboard::KeyCode::KEY_S)
		{
			m_speed.y = -100;
		}
		if (code == EventKeyboard::KeyCode::KEY_D)
		{
			m_speed.x = 100;
		}
		if (code == EventKeyboard::KeyCode::KEY_W)
		{
			m_speed.y = 100;
		}
	};

	lis->onKeyReleased = [this](EventKeyboard::KeyCode code, Event*)->void {
		m_speed = Vec2::ZERO;
	};

	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(lis, this);


	scheduleUpdate();

	return true;
}

void Block::update(float dt)
{
	this->setPosition(this->getPosition() + m_speed * dt);
}

